const app = getApp();
const regeneratorRuntime = global.regeneratorRuntime = require("../libs/regenerator");
const co = require("../libs/co");
const passport = require("../services/passport/passport");
const WxParse = require('../wxParse/wxParse.js');

Page({
    data: {
      tips: "",
      detailData: [],
      indicatorDots: true,
      autoplay: true,
      interval: 5000,
      duration: 1000,
      tips: "",
      hidden: false,
      selectedMenuIndex : 0,
      multiIndex: [],
      features:[],
      featureLength: 0,
      selectMsg: "",
      selectSkuId: 0,
      selectSkuAmount: 0,
      isHidden: false,
      productId : 0,
      isFavorite: false
    },
    onLoad: function(options) {
        app.launchOptions = options;
        /* !Do not Remove the follow line, used for build tool.*/
        let productId = options.id;
        this.setData({
          productId: productId
        });
        this.loadProduct(productId);
    },
    loadProduct: function (productId) {
      var that = this;
      co(function *() {
          let productService = require("../services/mall/productService");
          let product = yield productService.getProductInfo(productId);
          let featureLength = product.featureItems.length;
          for (let index = 0; index < featureLength; ++index) {
            that.data.multiIndex.push(0);
            that.data.features.push([]);
          }
          let contentText = product.contentText;
          WxParse.wxParse('detail', 'html', contentText, that, 5);

          console.log(product);
          that.setData({
            hidden: true,
            product: product,
            multiIndex: that.data.multiIndex,
            featureLength: featureLength,
            isFavorite: product.isFavorite
          });
          console.log("load");
          that.selectFeatureItems(0);
          //that.selectFeatureValue(that.data.multiIndex,-1);
      });
    },
    onMenuTouched: function(e) {
      var index = e.target.dataset.index;
      this.setData({
        selectedMenuIndex:index,
        isHidden: index == 0 ? false : true
      })
    },
    onAddCartTouched: function(e) {
      var that = this;
      co(function *() {
          let productId = that.data.productId;
          let skuId = that.data.selectSkuId;
          let selectSkuAmount = that.data.selectSkuAmount;
          let selectCount = 1;
          let cartService = require("../services/mall/cartService");
          let ret = yield cartService.addCartProduct(productId,skuId,selectSkuAmount,selectCount);
          if (ret) {
            wx.showToast({
             title: '添加成功',
             icon: 'success',
             duration: 1000
           });
         } else {
           wx.showToast({
            title: '添加失败',
            icon: 'warn',
            duration: 1000
          });
         }
      });
    },
    onCartList: function (e) {
      wx.switchTab({
          url: '/pages/page3',
      })
    },
    bindFeatureChange: function(e) {
        console.log("picker country 发生选择改变，携带值为", e.detail.value);
        var data = {
          multiIndex: this.data.multiIndex
        };
        data.multiIndex[e.detail.column] = e.detail.value;
        //this.selectFeatureValue(data.multiIndex, e.detail.column);
        this.selectFeatureItems(e.detail.column);
        /*switch (e.detail.column) {
          case  0:
              this.selectFeatureValue(data.multiIndex,0);
            break;
        }*/
        this.setData({
          multiIndex:data.multiIndex
        });
    },
    selectFeatureItems: function(selectIndex) {
      let multiIndex = this.data.multiIndex;
      let features = this.data.product.featureItems;
      let featureArras = [];

      for (let i = 0; i < this.data.featureLength; ++ i) {
        if (i <= selectIndex) {
          featureArras.push(features[i]);
        } else {
          console.log(multiIndex);
          let featureId = featureArras[i - 1][multiIndex[i - 1]].id;
          let newArr = this.selectChildFeature(features[i], i, featureId);
          featureArras.push(newArr);
          multiIndex[i] = multiIndex[i] >= newArr.length ? newArr.length - 1 : multiIndex[i];
        }
      }
      console.log(featureArras);
      this.setData({
        features: featureArras,
      });
      this.setSelectMsg();
      this.setSelectSku();
    },
    selectChildFeature: function (featureArras, index, featureId) {
      //index = index > 0 ? index - 1 : 0;
      console.log("index:" + index);
      console.log("feature:" + JSON.stringify(featureArras) + " fId:" + featureId);
      let newArr = [];
      let skus = this.data.product.skus;
      for (let i in skus) {
        let sFeatures = skus[i].features;
        if (sFeatures[index - 1].featureValueId == featureId) {
          for (let n in featureArras) {
            let item = featureArras[n];
            if (sFeatures[index].featureValueId == item.id) {
              console.log("featureSubId:" + sFeatures[index].featureValueId + " itemId:" + item.id);
              if (newArr.indexOf(item) == -1) {
                newArr.push(item);
              }
            }
          }
        }
      }
      return newArr;
    },
    setSelectMsg: function () {
      let msg = "";
      let features = this.data.features;
      let multiIndex = this.data.multiIndex;
      for (let i in features) {
        msg += features[i][multiIndex[i]].featureValue + ",";
      }
      this.setData({
        selectMsg: msg.length > 0 ? msg.substr(0,msg.length - 1) : ""
      });
    },
    setSelectSku: function () {
      let features = this.data.features;
      let multiIndex = this.data.multiIndex;
      let skus = this.data.product.skus;
      let skuId = 0;
      let skuAmount = 0;
      let isEqual = false;
      console.log(this.data.multiIndex);
      for(let i in skus) {
        let skuFeatires = skus[i].features;
        for (let n in skuFeatires) {
          console.log("fId:" + skuFeatires[n].featureValueId + " item.id:" + features[n][multiIndex[n]].id);
          isEqual = skuFeatires[n].featureValueId == features[n][multiIndex[n]].id ? true : false;
          if (!isEqual) {
            break;
          }
        }
        if (isEqual) {
          skuId = skus[i].id;
          skuAmount = skus[i].saleAmount;
          break;
        }
      }
      this.setData({
        selectSkuId: skuId,
        selectSkuAmount: skuAmount
      });
    },
    selectFeatureValue: function(multiIndex,selectIndex) {
      console.log(multiIndex);
      let features = this.data.product.featureItems;
      let featureItems = features[0];
      let featureSubs = selectIndex <= 0 ? [] : features[1];
      let featureSubItems = [];
      let featureId = featureItems.length > 0 ? featureItems[multiIndex[0]].id : -1;
      let featureSubId = featureSubs.length > 0 ? featureSubs[multiIndex[1]].id : -1;
      let isHaveSub = false;
      console.log("featureId:" + featureId + " featureSubId:" + featureSubId + " selectIndex:" + selectIndex);
      let skus = this.data.product.skus;

      for (var index in skus) {
        let sFeatures = skus[index].features;
        if (sFeatures[0].featureValueId == featureId) {
          if (selectIndex <= 0) {
            for (var i in features[1]) {
              let item = features[1][i];
              if (sFeatures[1].featureValueId == item.id) {
                console.log("featureSubId:" + sFeatures[1].featureValueId + " itemId:" + item.id);
                if (featureSubs.indexOf(item) == -1) {
                  featureSubs.push(item);
                }
              }
            }
            multiIndex[1] = multiIndex[1] >= featureSubs.length ? featureSubs.length - 1 : multiIndex[1];
            featureSubId = featureSubs.length > 0 ? featureSubs[multiIndex[1]].id : -1;
          }

          if (sFeatures[1].featureValueId == featureSubId) {
            for (var i in features[2]) {
              let item = features[2][i];
              if (sFeatures[2].featureValueId == item.id) {
                featureSubItems.push(item);
              }
            }
          }

          /*console.log(isHaveSub);
          if (isHaveSub) {

          } else {
            for (var i in features[2]) {
              let item = features[2][i];
              if (sFeatures[2].featureValueId == item.id) {
                featureSubItems.push(item);
              }
            }
          }*/
        }
      }
      this.data.features[0] = featureItems;
      this.data.features[1] = featureSubs;
      this.data.features[2] = featureSubItems;
      this.setData({
        features: this.data.features
      });
    },
    buyNow: function() {
      let skuId = this.data.selectSkuId;
      wx.navigateTo({
          url: '/pages/page10?skuId=' + skuId,
      });
    },
    onFavorite: function() {
      var that = this;
      co(function *() {
          let productId = that.data.productId;
          let skuId = that.data.selectSkuId;
          let productService = require("../services/mall/productService");
          if (!that.data.isFavorite) {
            let ret = yield productService.addFavorite(productId,skuId);
            that.setData({
              isFavorite: true
            });
            if (ret) {
              wx.showToast({
               title: '收藏成功',
               icon: 'success',
               duration: 1000
             });
           } else {
             wx.showToast({
              title: '收藏失败',
              icon: 'warn',
              duration: 1000
            });
          }
        } else {
            let productService = require("../services/mall/productService");
            let ret = yield productService.delFavorite(productId,skuId);
            if (ret) {
              that.setData({
                isFavorite: false
              });
            }
         }
      });
    },
    onReady:function(){
    },
    /* !Do not Remove the follow line, used for build tool.*/


    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
});
